package com.banksoft.cps.controller;




import com.banksoft.cps.bean.common.*;
import com.banksoft.cps.util.*;
import com.google.gson.Gson;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ControllerConstants {
    protected Logger logger = Logger.getLogger(ControllerConstants.class);

    public static final String ADMIN = "admin";

    public static final String SUPPLIER ="supplier";

    public static final String SHOP ="shop";

    public static final String CODE = "code";

    public static final Tip SUCCESS = new SuccessTip();
    public static final Tip ERROR = new ErrorTip(0, "");
    public static final Tip TIMEOUT = new ErrorTip(404,"登录超时");



    private static final Gson JSON_HELPER = new Gson();


    public String toJSONString(Object object) {
        return JSON_HELPER.toJson(object);
    }

    public static long calculatePageCount(int size, long count) {
        if (count == 0) {
            return 1;
        } else {
            return count % size == 0 ? count / size : count / size + 1;
        }
    }

    public static String reBack(String str, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println(str);
        out.close();
        return null;
    }

    protected String toExceptionString(Exception ex) {
        logger.error(ex);
        if (ex instanceof ServiceException) {
            return toJSONString(((ServiceException) ex).getErrorTip());
        } else {
            return toJSONString(new ErrorTip(1000, "系统错误"));
        }
    }


    protected Object getSessionObject(HttpSession session, String key){
        return session.getAttribute(key);
    }

    protected void clearSessionKey(HttpSession session, String key){
        session.removeAttribute(key);
    }

    /**
     * 保存上传的图片并返回服务器存储的图片名称
     *
     * @param servletContext
     * @param file
     * @return
     * @throws Exception
     */
    protected String saveUploadImage(ServletContext servletContext, MultipartFile file) throws Exception {
        if (file == null) {
            return toJSONString(new ErrorTip(2, "上传图片为空"));//上传图片为空
        }
        if (!FileUtil.isImage(file)) {
            throw new ServiceException(new ErrorTip(1, "不是正确的图片文件"));
        }
        long maxSize = 100000;//最大100000k
        try {
            ConfigHelper helper = ConfigHelper.getInstance();
            maxSize = Long.parseLong(helper.getConfig("yr.imgMaxSize"));
        } catch (Exception ex) {
            logger.error("图片文件上传限制大小错误" + maxSize, ex);
        }
        String path = "/upload/image/" + DateUtil.getDateStringByFormat(System.currentTimeMillis(), "yyyyMMdd");
        if (file.getSize() > maxSize * 1024) {
            //压缩图片
//            String descPathString = servletContext.getRealPath(path);
//            File descPath = new File(descPathString);
//            if (!descPath.exists()) {
//                descPath.mkdirs();
//            }
//            String fileName = DateUtil.getDateStringByFormat(System.currentTimeMillis(), "yyyyMMddHHmmssSSS") + "." + FileUtil.getFileExtendName(file.getOriginalFilename());
//            String descFilePath = descPathString + File.separator + fileName;
//            File tagetFile = new File(descFilePath);
//            file.transferTo(tagetFile);
//            ZipImageUtil.zipImageFile(tagetFile,tagetFile,400,0,0.7f);
//            String fullPath = path + File.separator + fileName;
//            fullPath = fullPath.replaceAll("\\\\", "/");
//            return fullPath;
            throw new ServiceException(new ErrorTip(3, "上传文件过大，最大支持" + maxSize + "K"));
        }
        //System.out.println("File size:" + file.getSize());

        return saveBackPath(servletContext, file, path);
    }

    /**
     * 保存上传的flash并返回服务器存储的文件名称
     *
     * @param servletContext
     * @param file
     * @return
     * @throws Exception
     */
    protected String saveUploadFlash(ServletContext servletContext, MultipartFile file) throws Exception {
        if (file == null) {
            return toJSONString(new ErrorTip(2, "上传文件为空"));//上传文件为空
        }
        if (!FileUtil.isFlash(file)) {
            throw new ServiceException(new ErrorTip(1, "上传文件扩展名是不允许的扩展名"));
        }
        String path = "/upload/flash/" + DateUtil.getDateStringByFormat(System.currentTimeMillis(), "yyyyMMdd");
        return saveBackPath(servletContext, file, path);
    }

    /**
     * 保存上传的media并返回服务器存储的文件名称
     *
     * @param servletContext
     * @param file
     * @return
     * @throws Exception
     */
    protected String saveUploadMedia(ServletContext servletContext, MultipartFile file) throws Exception {
        if (file == null) {
            return toJSONString(new ErrorTip(2, "上传文件为空"));//上传文件为空
        }
        if (!FileUtil.isMedia(file)) {
            throw new ServiceException(new ErrorTip(1, "上传文件扩展名是不允许的扩展名"));
        }
        String path = "/upload/media/" + DateUtil.getDateStringByFormat(System.currentTimeMillis(), "yyyyMMdd");
        return saveBackPath(servletContext, file, path);
    }

    /**
     *判断导入的excel文件
     */
    protected String saveUploadExcelFile(MultipartFile file, HttpServletRequest request) throws IOException, ServiceException {
        if (file == null || StringUtil.isNullOrEmpty(file.getOriginalFilename())) {
            throw new ServiceException(new ErrorTip(1,"上传文件为空"));//上传文件为空
        }
        // 获得文件后缀名
        String filePathName = file.getOriginalFilename();//上传文件本地路径
        String extendName = filePathName.substring(filePathName.lastIndexOf(".") + 1, filePathName.length());
        if(!"xls".equals(extendName.toLowerCase()) && !"xlsx".equals(extendName.toLowerCase())) {
            throw new ServiceException(new ErrorTip(2,"上传文件格式不正确，只能上传后缀名为xls或者xlsx的excel文件"));
        }
        String path = "/upload/" + DateUtil.getDateStringByFormat(System.currentTimeMillis(), "yyyyMMdd");
        String filePath = saveBackPath(request.getSession().getServletContext(), file, path);  //保存导入文件
        return filePath;
    }
    /**
     * 保存上传的文件并返回服务器存储的文件名称
     *
     * @param servletContext
     * @param file
     * @return
     * @throws Exception
     */
    protected String saveUploadFile(ServletContext servletContext, MultipartFile file) throws Exception {
        if (file == null) {
            return toJSONString(new ErrorTip(2, "上传文件为空"));//上传文件为空
        }
        if (!FileUtil.isFile(file)) {
            throw new ServiceException(new ErrorTip(1, "上传文件扩展名是不允许的扩展名"));
        }
        String path = "/upload/file/" + DateUtil.getDateStringByFormat(System.currentTimeMillis(), "yyyyMMdd");
        return saveBackPath(servletContext, file, path);
    }


    protected String saveBackPath(ServletContext servletContext, MultipartFile file, String path) throws IOException {
        String descPathString = servletContext.getRealPath(path);
        File descPath = new File(descPathString);
        if (!descPath.exists()) {
            descPath.mkdirs();
        }
        String fileName = DateUtil.getDateStringByFormat(System.currentTimeMillis(), "yyyyMMddHHmmssSSS") + "." + FileUtil.getFileExtendName(file.getOriginalFilename());
        String descFilePath = descPathString + File.separator + fileName;
        file.transferTo(new File(descFilePath));
        String fullPath = path + File.separator + fileName;
        fullPath = fullPath.replaceAll("\\\\", "/");
        return fullPath;
    }

    protected String getRequestIp(HttpServletRequest request) {
        try{
            String ip = request.getHeader("x-forwarded-for");
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }

            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }

            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
            return ip;
        } catch (Exception e) {
            return request.getRemoteAddr();
        }
    }



    protected ErrorTip createErrorTip(String message) {
        return new ErrorTip(999,message);
    }

    protected DataTip createDataTip(Object data) {
        return new DataTip(true, "", data);
    }


    protected String domain(HttpServletRequest request){
        String domain = request.getServerName();
        int port = request.getServerPort();
        if(port != 80) {
            domain += ":" + port;
        }
        domain = "http://" + domain;
        return domain;
    }

    //APP接口装换内容，将内容中的图片路径拼接域名
    protected String convertContent(String content, HttpServletRequest request){
        if(StringUtil.isNullOrEmpty(content)) return content;
        String domain = domain(request);
        Pattern pattern = Pattern.compile("<img[^>]*src=\"([^\"]*)\"[^>]*[^>]*>");
        Matcher matcher = pattern.matcher(content);
        while (matcher.find()) {
            String temp = matcher.group(1);
            if (!temp.substring(0,7).equals("http://") && !temp.substring(0,8).equals("https://")){
                content = content.replaceAll(temp, domain + temp);
            }
        }
        return content;
    }

    /**
     *
     * @param code
     * @param msg
     * @param list
     * @param count
     * @return
     */
    protected Map<String,Object> buildNewPage(String code, String msg, List list, long count){
        Map<String,Object> map = new HashMap<>();
        map.put("code",code);
        map.put("msg",msg);
        map.put("data",list);
        map.put("count", count);
        return map;
    }
    public String getWebPath(HttpServletRequest request)
    {
        String path = request.getSession().getServletContext().getRealPath("/");
        return path;
    }
    protected Map<String,Object> buildNewPage(List list, long count) {
        return buildNewPage("0","", list,count);
    }
}
